import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../core/utils/show_toast.dart';
import '../../../data/controllers/attendances_controller.dart';
import '../models/attendance.dart';

part 'attendances_list_state.dart';

class AttendancesListCubit extends Cubit<AttendancesListState> {
  AttendancesListCubit() : super(AttendancesListInitial());

  static AttendancesListCubit get(context) => BlocProvider.of(context);

  List<Attendance> attendances = [];
  late DateTime startDate;
  late DateTime endDate;
  late String? exerciseId;

  void init({ required DateTime startDate,
    required  DateTime endDate,
    String? exerciseId,}) {

    this.startDate = startDate;
    this.endDate = endDate;
    this.exerciseId = exerciseId;

    getAllAttendances();
  }

  Future<void> getAllAttendances() async {
    attendances = [];
    emit(AttendancesListLoading());
    await AttendancesController.getAttendancesByDate( startDate: startDate , endDate: endDate, exerciseId:exerciseId ,).catchError((e) {
      emit(AttendancesListError());
      return null;
    }).then((value) {
      if (value != null && value.state) {
        attendances = List<Attendance>.generate(value.data.length, (index) =>
            Attendance.fromJson(value.data[index]));
        emit(AttendancesListDone());
      } else if (value != null) {
        showMessage(value.message);
        emit(AttendancesListError());
      } else {
        if (kDebugMode) {
          print('value is null');
        }
        emit(AttendancesListError());
      }
    });
  }

}
